package query.controller;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import query.bean.Question;
import query.bean.Questionnaire;
import query.bean.User;
import query.db.PaperRepository;
import query.db.QuestionnaireRepository;
import query.db.UserRepository;

/**
 * 用户行为控制类
 * 
 * @author lzy
 * @version 1.0.4
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {

	/**
	 * 用户数据库操作对象
	 */
	@Autowired
	private UserRepository userRepository;

	/**
	 * 问卷数据库操作对象
	 */
	@Autowired
	private QuestionnaireRepository questionnaireRepository;

	/**
	 * 答卷数据库操作对象
	 */
	@Autowired
	private PaperRepository paperRepository;

	private final static int PAGE = 4;

	/**
	 * 获取用户主页
	 * 
	 * @return用户主页
	 */
	@RequestMapping(value = "", method = GET)
	public String getUserPage() {
		return "userpage";
	}

	/**
	 * 处理修改用户信息
	 * 
	 * @param userName 用户名
	 * @param email    电子邮箱
	 * @param phone    电话号码
	 * @return 操作结果
	 */
	@RequestMapping(value = "/updateInfo", method = POST)
	@ResponseBody
	public String processUpdateInfo(String userName, String email, String phone, HttpSession session) {
		userRepository.update(userName, email, phone);
		User user = (User) session.getAttribute("user");
		user.setEmail(email);
		user.setPhone(phone);
		session.setAttribute("user", user);
		return "true";
	}

	/**
	 * 获取修改密码页面
	 * 
	 * @return 修改密码页码
	 */
	@RequestMapping(value = "/updatePassword", method = GET)
	public String getUpdatePassword() {
		return "updatePassword";
	}

	/**
	 * 处理密码修改
	 * 
	 * @return 操作结果
	 */
	@RequestMapping(value = "/updatePassword", method = POST)
	@ResponseBody
	public String processUpdatePassword(String oldPassword, String newPassword, HttpSession session) {
		User user = (User) session.getAttribute("user");
		if (userRepository.search(user.getUserName(), oldPassword) == null) {
			return "false";
		} else {
			userRepository.update(user.getUserName(), newPassword);
			return "true";
		}
	}

	/**
	 * 获取创建问卷页面
	 * 
	 * @return 创建问卷页面
	 */
	@RequestMapping(value = "/addQuery", method = GET)
	public String getAdd() {
		return "addQuestion";
	}

	/**
	 * 处理创建问卷
	 * 
	 * @param questions 问卷问题信息JSON字符串
	 * @return 操作结果及问卷链接
	 */
	@RequestMapping(value = "/addQuery", method = POST)
	@ResponseBody
	public String processAdd(String questions, HttpSession session) {
		User user = (User) session.getAttribute("user");
		if (user == null) {
			return "false";
		}
		List<Question> list = JSON.parseArray(questions, Question.class);
		Questionnaire questionnaire = questionnaireRepository.insertQuestionnaire(user.getUserName(),
				list.get(0).getDescription());
		if (questionnaire == null) {
			return "false";
		}
		for (int i = 1; i < list.size(); i++) {
			list.get(i).setQuestionnaireId(questionnaire.getId());
			questionnaireRepository.insertQuestion(list.get(i));
		}
		return String.valueOf(questionnaire.getId());
	}

	/**
	 * 获取问卷查询页面
	 * 
	 * @param session 用户session
	 * @return 问卷查询页面
	 */
	@RequestMapping(value = "/search", method = GET)
	public String getSearch(HttpSession session) {
		Integer integer = (Integer) session.getAttribute("queryPage");
		if (integer == null) {
			integer = new Integer(1);
			session.setAttribute("queryPage", integer);
		}
		int page = integer.intValue();
		String title = (String) session.getAttribute("searchTitle");
		if (title != null) {
			return "searchQuestion";
		}
		User user = (User) session.getAttribute("user");
		List<Questionnaire> list = questionnaireRepository.searchQuestionnaires(user.getUserName(), (page - 1) * PAGE,
				PAGE);
		session.setAttribute("queryList", list);
		return "searchQuestion";
	}

	/**
	 * 处理问卷查询
	 * 
	 * @param session 用户查询
	 * @return 操作结果
	 */
	@RequestMapping(value = "/search", method = POST)
	@ResponseBody
	public String processSearchQuery(String title, HttpSession session) {
		if (title == null || title.equals("")) {
			session.setAttribute("queryPage", new Integer(1));
			session.removeAttribute("searchTitle");
			return "true";
		} else {
			List<Questionnaire> list = questionnaireRepository.searchQuestionnaire(title, 0, PAGE);
			if (list == null || list.size() == 0) {
				return "false";
			} else {
				session.setAttribute("queryList", list);
				session.setAttribute("searchTitle", title);
				session.setAttribute("queryPage", new Integer(1));
				return "true";
			}
		}
	}

	/**
	 * 处理问卷查看分页操作
	 * 
	 * @param page    要获取页面的页码
	 * @param session 用户session
	 * @return 操作结果
	 */
	@RequestMapping(value = "/gotoPage", method = POST)
	@ResponseBody
	public String processGotoPage(String page, HttpSession session) {
		int temp;
		try {
			temp = Integer.valueOf(page);
		} catch (Exception e) {
			temp = 1;
		}
		User user = (User) session.getAttribute("user");
		String title = (String) session.getAttribute("searchTitle");
		if (title != null) {
			List<Questionnaire> list = questionnaireRepository.searchQuestionnaire(title, (temp - 1) * PAGE, PAGE);
			if (list.size() != 0) {
				session.setAttribute("queryList", list);
				session.setAttribute("queryPage", new Integer(temp));
				return "true";
			} else {
				return "false";
			}
		}
		List<Questionnaire> list = questionnaireRepository.searchQuestionnaires(user.getUserName(), (temp - 1) * PAGE,
				PAGE);
		if (list.size() != 0) {
			session.setAttribute("queryList", list);
			session.setAttribute("queryPage", new Integer(temp));
			return "true";
		} else {
			return "false";
		}
	}

	/**
	 * 处理删除问卷
	 * 
	 * @param id 要删除问卷的id
	 * @return 重定向问卷查询页面
	 */
	@RequestMapping(value = "/delete/{id}", method = GET)
	public String processDelete(@PathVariable("id") long id) {
		paperRepository.deletePapers(id);
		questionnaireRepository.deleteQuestionnaire(id);
		return "redirect:/user/search";
	}

	/**
	 * 更新问卷状态
	 * 
	 * @param id     问卷id
	 * @param choice 要更新的状态
	 * @return 重定向问卷查询页面
	 */
	@RequestMapping(value = "/close/{id}/{choice}", method = GET)
	public String processClose(@PathVariable("id") long id, @PathVariable("choice") int choice) {
		if (choice == 1) {
			questionnaireRepository.updateClose(id, true);
		} else {
			questionnaireRepository.updateClose(id, false);
		}
		return "redirect:/user/search";
	}

	/**
	 * 处理查看问卷具体题目
	 * 
	 * @param id      问卷id
	 * @param session 用户session
	 * @return 问卷具体题目页面
	 */
	@RequestMapping(value = "/questions/{id}", method = GET)
	public String processQuestions(@PathVariable("id") long id, HttpSession session) {
		if (id == 0) {
			return "question";
		}
		List<Question> list = questionnaireRepository.searchQuestions(id);
		session.setAttribute("questionList", list);
		return "question";
	}
}